#import "DDLoginViewController.h"
#import "DDLoginInput.h"
#import "DDPlatform.h"
#import "DDWebView.h"
#import "TCCIAP.h"
@interface DDLoginViewController ()
@property (nonatomic, strong) DDLoginInput *input;
@property (nonatomic, strong) DDButton *Btn;
@property (nonatomic, strong) DDButton *registerBtn;
@property (nonatomic, strong) DDButton *forgetPWDBtn;
@property (nonatomic, strong) DDButton *serviceBtn;
@property (nonatomic, strong) DDWebView *webView;
@property (nonatomic, strong) NSDictionary *accountDict;
@end
@implementation DDLoginViewController
- (void)viewDidLoad {
    [super viewDidLoad];
}
- (DDLoginInput *)input
{
    if (!_input)
    {
        _input = [[DDLoginInput alloc] init];
        [self.ddview addSubview:_input];
        _input.c_bottom.c_equal(self.ddview.c_centerY).with.coffset(-GAP);
        _input.c_left.c_equal(self.ddview).with.coffset(GAP);
        _input.c_right.c_equal(self.ddview).with.coffset(-GAP);
        _input.c_height.c_equal(TEXTFILDHEIGHT * 2);
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
            _input.c_bottom.c_equal(self.ddview.c_centerY).with.coffset(-GAP * 2);
        else
            _input.c_bottom.c_equal(self.ddview.c_centerY).with.coffset(-GAP);
    }
    return _input;
}
- (DDButton *)Btn
{
    if (!_Btn)
    {
        _Btn = [[DDButton alloc] init];
        _Btn.title = @"立即登录";
        _Btn.backgroundColor = [DDHelper help].color;
        _Btn.layer.cornerRadius = GAP / 2.0;
        [_Btn addTarget:self action:@selector(dd_actionForLogin) forControlEvents:UIControlEventTouchUpInside];
        [self.ddview addSubview:_Btn];
        _Btn.c_left.c_equal(self.input);
        _Btn.c_right.c_equal(self.input);
        _Btn.c_height.c_equal(BUTTONHEIGHT);
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
            _Btn.c_top.c_equal(self.ddview.c_centerY).with.coffset(GAP * 2);
        else
            _Btn.c_top.c_equal(self.ddview.c_centerY).with.coffset(GAP);
    }
    return _Btn;
}
- (DDButton *)forgetPWDBtn
{
    if (!_forgetPWDBtn)
    {
        _forgetPWDBtn = [[DDButton alloc] init];
        _forgetPWDBtn.title = @"忘记密码";
        _forgetPWDBtn.font = FONT(UIFontWeightRegular, 15);
        [_forgetPWDBtn setValue:[DDHelper help].color forKeyPath:@"_label.textColor"];
        _forgetPWDBtn.autoTitleSize = YES;
        [_forgetPWDBtn addTarget:self action:@selector(dd_actionForForgetPWD) forControlEvents:UIControlEventTouchUpInside];
        [self.ddview addSubview:_forgetPWDBtn];
        _forgetPWDBtn.c_top.c_equal(self.Btn.c_bottom).with.coffset(GAP);
        _forgetPWDBtn.c_left.c_equal(self.input);
    }
    return _registerBtn;
}
- (DDButton *)registerBtn
{
    if (!_registerBtn)
    {
        _registerBtn = [[DDButton alloc] init];
        _registerBtn.title = @"去注册>>";
        _registerBtn.font = FONT(UIFontWeightRegular, 15);
        [_registerBtn setValue:[DDHelper help].color forKeyPath:@"_label.textColor"];
        _registerBtn.autoTitleSize = YES;
        [_registerBtn addTarget:self action:@selector(dd_actionForRegister) forControlEvents:UIControlEventTouchUpInside];
        [self.ddview addSubview:_registerBtn];
        _registerBtn.c_top.c_equal(self.Btn.c_bottom).with.coffset(GAP);
        _registerBtn.c_right.c_equal(self.input);
    }
    return _registerBtn;
}
- (DDButton *)serviceBtn
{
    if (!_serviceBtn)
    {
        _serviceBtn = [[DDButton alloc] init];
        _serviceBtn.title = @"如有疑问，请联系客服QQ";
        _serviceBtn.font = FONT(UIFontWeightRegular, 15);
        [_serviceBtn setValue:[DDHelper help].color forKeyPath:@"_label.textColor"];
        _serviceBtn.autoTitleSize = YES;
        [_serviceBtn addTarget:self action:@selector(dd_actionForServiceBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.ddview addSubview:_serviceBtn];
        _serviceBtn.c_bottom.c_equal(self.ddview).with.coffset(-GAP);
        _serviceBtn.c_centerX.c_equal(self.ddview);
    }
    return _serviceBtn;
}
- (DDWebView *)webView
{
    if (!_webView)
    {
        _webView = [[DDWebView alloc] init];
        [self.view addSubview:_webView];
    }
    return _webView;
}
- (NSDictionary *)accountDict
{
    return @{@"name":self.input.nameTF.text,@"password":self.input.passTF.text};
}
- (void)dd_autoInput:(int)index
{
    if ([[DDHelper help].accountArr count] > index)
    {
        NSString *jsonString = [DDHelper help].accountArr[index];
        self.input.nameTF.text = [[[jsonString dict] allKeys] firstObject];
        self.input.passTF.text = [[[jsonString dict] allValues] firstObject];
    }
}
- (void)dd_pop:(void (^)(void))block
{
    if ([[DDHelper help].audistate containsString:@"0"])
    {
        [super dd_pop:block];
    }
    else
    {
        [CCHud startHud];
        [self.request dd_loginRequestWithBlock:^(NSDictionary *dict) {
            [CCHud stopHud];
            int code = -1;
            code = [[dict valueForKey:@"code"] intValue];
            if (code == 0)
            {
                [[DDHelper help] setValue:[dict valueForKey:@"accountid"] forKey:@"accountID"];
                [[DDHelper help] setValue:[dict valueForKey:@"accesstoken"] forKey:@"token"];
                [[DDHelper help] setValue:[dict valueForKey:@"gameaccountid"] forKeyPath:@"gameAccountID"];
                [TCCIAP dd_checkQueueAndDB];
                [CCNotice post:DDPlatformLoginNotification obj:nil info:@{@"token":[DDHelper help].token,@"accountID":[DDHelper help].accountID,@"link":[DDHelper help].link}];
            }
            else
            {
                [CCAlert showMessage:[NSString stringWithFormat:@"%@",[dict valueForKey:@"info"]] title:@"错误" enter:nil];
            }
        }];
    }
}
- (void)dd_actionForLogin
{
    DeLog(@"立即登录");
    if ([self.input.nameTF.text length] <1) return [CCAlert showMessage:@"请输入账号(6～12位数字或字母)" hidden:nil];
    else if ([self.input.passTF.text length] <1) return [CCAlert showMessage:@"请输入密码" hidden:nil];
    //        else if (![self.input.nameTF.text isMobile]) return [CCAlert dd_showMessage:@"手机号码格式错误" hidden:nil];
    else if ([self.input.nameTF.text length] < 6 || [self.input.nameTF.text length] > 12) return [CCAlert showMessage:@"账号限定6～12位" hidden:nil];
    else if (![self.input.nameTF.text isNumberOrAlphabet]) return [CCAlert showMessage:@"号码仅限于字母和数字" hidden:nil];
    
    else if ([self.input.nameTF.text length] < 6 || [self.input.nameTF.text length] > 12) return [CCAlert showMessage:@"账号限定6～12位" hidden:nil];
    else if (![self.input.nameTF.text isNumberOrAlphabet]) return [CCAlert showMessage:@"号码仅限于字母和数字" hidden:nil];
    [CCHud startHud];
    [self.request dd_loginRequest:self.accountDict];
}
- (void)dd_actionForForgetPWD
{
    [self presentViewController:[NSClassFromString(@"DDResetPWDViewController") new] animated:YES completion:nil];
}
- (void)dd_actionForRegister
{
    [self presentViewController:[NSClassFromString(@"DDRegisterViewController") new] animated:YES completion:nil];
}
- (void)dd_actionForServiceBtn
{
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]])
    {
        [self.webView dd_show:[NSString stringWithFormat:@"mqq://im/chat?chat_type=wpa&uin=%@&version=1&src_type=web",[DDHelper help].qq]];
    }
    else
    {
        [CCAlert showMessage:@"未安装QQ,请先安装" title:@"注意" enter:nil];
    }
}
#pragma mark - JTWRequestDelegate
- (void)dd_didRequestWithReceiveData:(NSDictionary *)dict error:(NSError *)error
{
    [CCHud stopHud];
    if(error)
    {
        if ((error.code != -999 || ![error.localizedDescription isEqualToString:@"cancelled"]))
            [CCAlert showMessage:[NSString stringWithFormat:@"%@",error.localizedDescription] hidden:nil];
        return;
    }
    if (!dict)
        return;
    int code = -1;
    code = [[dict valueForKey:@"code"] intValue];
    NSString *info = [NSString stringWithFormat:@"%@",[dict valueForKey:@"info"]];
    if (code == 0)
    {
        [DDHelper dd_insertAccountDict:self.accountDict];
        NSString *phone = [dict valueForKey:@"phone"];
        [[DDHelper help] setValue:self.input.nameTF.text forKey:@"account"];
        [[DDHelper help] setValue:[dict valueForKey:@"accountid"] forKey:@"accountID"];
        [[DDHelper help] setValue:[dict valueForKey:@"accesstoken"] forKey:@"token"];
        [[DDHelper help] setValue:[dict valueForKey:@"gameaccountid"] forKeyPath:@"gameAccountID"];
        [[DDHelper help] setValue:[phone length] > 1?phone:@"" forKeyPath:@"phone"];
        [TCCIAP dd_checkQueueAndDB];
        [CCAlert showMessage:(([info length] > 1)?info:@"登录成功") hidden:^{
            [[[UIApplication sharedApplication].delegate window] makeKeyAndVisible];
            [self dismissViewControllerAnimated:YES completion:^{
                [CCNotice post:DDPlatformLoginNotification obj:nil info:@{@"token":[DDHelper help].token,@"accountID":[DDHelper help].accountID,@"link":[DDHelper help].link}];
                [DDHelper help].userBtn.hidden = ([[DDHelper help].state intValue] == 1)?NO:YES;
            }];
        }];
        [DDPlatform updateRoleInfo:@{@"serverid":@"123",
                                     @"servername":@"333",
                                     @"roleid":@"321",
                                     @"rolename":@"juse",
                                     @"rolelevel":@"2121"
        }];
    }
    else
    {
        [CCAlert showMessage:info title:@"错误" enter:nil];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //    self.registerBtn.hidden = [[[DDHelper help] valueForKey:@"extstate"] isEqualToString:@"0"]?NO:YES;
    [self reload];
}
- (void)reload
{
    self.forgetPWDBtn.hidden = NO;
    self.registerBtn.hidden = [[[DDHelper help] valueForKey:@"hidestate"] isEqualToString:@"0"]?NO:YES;
    self.serviceBtn.hidden = NO;
    self.input.nameTF.placeholder = @"输入账号";
    self.input.passTF.placeholder = @"登录密码";
    [self.input bringSubviewToFront:[self.input valueForKeyPath:@"_line"]];
    [self dd_autoInput:0];
}
@end
